# Copyright 2009 http://www.yuntien.com
# Licensed under the Apache License, Version 2.0

from ytblog.controller.common import *
from ytblog.lib.rss import PyRSS2Gen
from ytblog.helper.url import *
import urllib

class BlogRSSController(BlogController):
      
  def get(self):
    query = self.request.GET
    
    blogs_query = Blog.all().order('-date')
    
    if query.has_key('tag'):
      blogs_query = blogs_query.filter('tags =', query['tag'])
      
    if ytblog.config.USE_PROMOTION:
      blogs_query = blogs_query.filter('popular =', True)       
      
    self.get_rss(blogs_query)
    
  def get_rss(self, query):
    blogs = query.fetch(ytblog.config.BLOG_NUM_PER_PAGE)

    if self.request.get('tag', ''):
      title = self.request.get('tag', '') + ' - ' + ytblog.config.CONFIG['site_title']
    else:
      title = ytblog.config.CONFIG['site_title']  
    
    rss = PyRSS2Gen.RSS2(
      title = title,
      link = self.request.host_url,
      description = ytblog.config.CONFIG['site_title'],
      lastBuildDate = datetime.datetime.now(),
      items = [self.get_rss_item(blog) for blog in blogs])

    self.response.headers['Content-Type'] = 'application/rss+xml; charset=utf-8'
    self.response.out.write(rss.to_xml(encoding='utf-8'))
       
  def get_rss_item(self, blog):
    return PyRSS2Gen.RSSItem(
      title = blog.title,
      link = self.request.host_url + get_blog_url(blog),
      description = blog.content,
      author = blog.author.nickname(),
      guid = PyRSS2Gen.Guid(self.request.host_url + get_blog_url(blog)),
      pubDate = blog.date )
    